package com.ggh.jinjilive.views.live.music;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.ggh.jinjilive.R;
import com.ggh.jinjilive.listener.AddItemOnClickListener;
import com.ggh.jinjilive.listener.AddOnClickListener;
import com.ggh.jinjilive.listener.AddOnClickListener1;
import com.ggh.jinjilive.mobile.live.MusicList;
import com.ggh.jinjilive.utils.CommonUtils;
import com.ggh.jinjilive.utils.GeneralUtils;
import com.ggh.jinjilive.views.live.music.adapter.BGMRecyclerViewAdapter;
import com.ggh.jinjilive.views.live.music.adapter.ReverberationAdapter;
import com.ggh.jinjilive.views.live.music.adapter.VoiceAdapter;
import com.ggh.jinjilive.views.live.music.mobile.ItemEntity;
import com.ggh.jinjilive.views.live.music.utils.ListUtils;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tencent.liteav.audio.TXAudioEffectManager;

import java.util.List;

public class MusicMixer extends LinearLayout {
    private Context mContext;
    //关闭
    private LinearLayout ll_occlude;
    //调音台
    private LinearLayout ll_music_view;
    //音乐列表页面
    private LinearLayout ll_music_list;
    //选择音乐
    private Button mBtnSelectedSong;
    //
    private BGMListener mBGMPlayListenr;
    //开始播放
    private LinearLayout ll_music;
    private TextView mTvTotalTime;
    private TextView mTvStartTime;
    private ImageButton mImgbtnBGMPlay;
    //是否正在播放
    private boolean mIsPlaying = false;
    //背景音乐
    private TextView tv_bgm;
    //音乐列表关闭
    private ImageView img_occlude;


    //音乐音量
    private SeekBar mSbBGMVolume;
    private TextView mTvBGMVolume;
    private int mBGMVolume = 100;
    private int mBGMId = -1;
    //人声音量
    private SeekBar mSbMicVolume;
    private TextView mTvMicVolume;

    //音乐升降调
    private SeekBar mSbPitchLevel;
    private TextView mTvPitchLevel;
    private float mPitch = 0;
    //变声
    private RecyclerView mRVAuidoChangeType;
    private List<ItemEntity> mChangerItemEntityList;
    private VoiceAdapter mChangerRVAdapter;
    //混响效果
    private RecyclerView mRVAudioReverbType;
    private List<ItemEntity> mReverbItemEntityList;
    private ReverberationAdapter reverberationAdapter;
    //音乐
    //搜索内容
    private String keywords = "";
    private RecyclerView mRVAudioBGM;
    private SmartRefreshLayout mRVAudioBGMSmart;
    private BGMRecyclerViewAdapter mBGMRVAdapter;

    //设置控制台
    private TXAudioEffectManager mAudioEffectManager;
    //当前播放的地址
    private MusicList musicList;
    public void setAudioEffectManager(TXAudioEffectManager audioEffectManager) {
        mAudioEffectManager = audioEffectManager;
    }

    //关闭控制台
    private AddOnClickListener addOnClickListener;
    public void setAddOnClickListener(AddOnClickListener addOnClickListener){
        this.addOnClickListener = addOnClickListener;
    }

    public MusicMixer(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.layout_music_mixer, this);
        initView();
    }



    private void initView() {
        //关闭
        ll_occlude = findViewById(R.id.ll_occlude);
        ll_occlude.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(null != addOnClickListener){
                    addOnClickListener.onSkipClicked("关闭");
                }
            }
        });
        //调音台
        ll_music_view = findViewById(R.id.ll_music_view);
        //音乐列表控件
        ll_music_list = findViewById(R.id.ll_music_list);
        //选择音乐
        mBtnSelectedSong = (Button) findViewById(R.id.audio_btn_select_song);
        mBtnSelectedSong.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //调音台
                ll_music_view.setVisibility(GONE);
                //音乐列表控件
                ll_music_list.setVisibility(VISIBLE);
            }
        });
        //开始播放
        ll_music = findViewById(R.id.ll_music);
        mTvStartTime = findViewById(R.id.tv_bgm_start_time);
        mTvTotalTime = findViewById(R.id.tv_bgm_end_time);
        mImgbtnBGMPlay = findViewById(R.id.ib_audio_bgm_play);

        //背景音乐
        tv_bgm = findViewById(R.id.tv_bgm);
        tv_bgm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //调音台
                ll_music_view.setVisibility(GONE);
                //音乐列表控件
                ll_music_list.setVisibility(VISIBLE);
            }
        });
        img_occlude = findViewById(R.id.img_occlude);
        img_occlude.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //调音台
                ll_music_view.setVisibility(VISIBLE);
                //音乐列表控件
                ll_music_list.setVisibility(GONE);
            }
        });

        //音乐音量
        mTvBGMVolume = findViewById(R.id.tv_bgm_volume);
        mSbBGMVolume = findViewById(R.id.sb_bgm_volume);
        mSbBGMVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mTvBGMVolume.setText(progress + "");
                mBGMVolume = progress;
                if (mAudioEffectManager != null && mBGMId != -1) {
                    mAudioEffectManager.setMusicPlayoutVolume(mBGMId, progress);
                    mAudioEffectManager.setMusicPublishVolume(mBGMId, progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        //人声音量
        mSbMicVolume = findViewById(R.id.sb_mic_volume);
        mTvMicVolume = findViewById(R.id.tv_mic_volume);
        mSbMicVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mTvMicVolume.setText(progress + "");
                if (mAudioEffectManager != null) {
                    mAudioEffectManager.setVoiceCaptureVolume(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        //音乐升降调
        mTvPitchLevel = findViewById(R.id.tv_pitch_level);
        mSbPitchLevel = findViewById(R.id.sb_pitch_level);
        mSbPitchLevel.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                float pitch = ((progress - 50) / (float) 50);
                mTvPitchLevel.setText(pitch + "");
                mPitch = pitch;
                if (mAudioEffectManager != null && mBGMId != -1) {
                    LogUtils.d("setMusicPitch: mBGMId -> " + mBGMId + ", pitch -> " + pitch);
                    mAudioEffectManager.setMusicPitch(mBGMId, pitch);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        //变声
        mChangerItemEntityList = ListUtils.createAudioChangeItems(mContext);
        mRVAuidoChangeType = findViewById(R.id.audio_change_type_rv);
        mChangerRVAdapter = new VoiceAdapter();
        mChangerRVAdapter.setAdd(mChangerItemEntityList);
        mChangerRVAdapter.setAddItemOnClickListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {

                ItemEntity itemEntity = (ItemEntity) mObject;
                if(null != itemEntity){
                    //变声
                    if (mAudioEffectManager != null) {
                        mAudioEffectManager.setVoiceChangerType(ListUtils.translateChangerType(itemEntity.mType));
                    }
                    for (int i = 0 ; i <  mChangerItemEntityList.size(); i++) {
                        if (position == i) {
                            mChangerItemEntityList.get(i).mIsSelected = true;
                        } else {
                            mChangerItemEntityList.get(i).mIsSelected = false;
                        }
                    }
                    mChangerRVAdapter.notifyDataSetChanged();

                }
            }
        });
        LinearLayoutManager reverbLayoutManager = new LinearLayoutManager(mContext);
        reverbLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRVAuidoChangeType.setLayoutManager(reverbLayoutManager);
        mRVAuidoChangeType.setAdapter(mChangerRVAdapter);
        //混响效果
        mReverbItemEntityList  = ListUtils.createReverbItems(mContext);
        mRVAudioReverbType = findViewById(R.id.audio_reverb_type_rv);
        reverberationAdapter = new ReverberationAdapter();
        reverberationAdapter.setAdd(mReverbItemEntityList);
        reverberationAdapter.setAddItemOnClickListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                ItemEntity itemEntity = (ItemEntity) mObject;
                if(null != itemEntity){
                    if (mAudioEffectManager != null) {
                        mAudioEffectManager.setVoiceReverbType(ListUtils.translateReverbType(itemEntity.mType));
                    }
                    for (int i = 0 ; i <  mReverbItemEntityList.size(); i++) {
                        if (position == i) {
                            mReverbItemEntityList.get(i).mIsSelected = true;
                        } else {
                            mReverbItemEntityList.get(i).mIsSelected = false;
                        }
                    }
                    reverberationAdapter.notifyDataSetChanged();
                }
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRVAudioReverbType.setLayoutManager(layoutManager);
        mRVAudioReverbType.setAdapter(reverberationAdapter);
        //获取音乐列表
        initMusicSelect();

    }

    /**
     * 音乐选择
     */
    private void initMusicSelect() {

        //音乐列表控件
        mRVAudioBGM = findViewById(R.id.recyclerView);
        mRVAudioBGM.setLayoutManager(new LinearLayoutManager(mContext));
        mBGMRVAdapter = new BGMRecyclerViewAdapter();
        mBGMRVAdapter.setAddItemOnClickListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                musicList = (MusicList) mObject;
                if(null != musicList){
                    playSong(position);
                }
            }
        });
        mRVAudioBGM.setAdapter(mBGMRVAdapter);
        //音乐列表控件  刷新
        mRVAudioBGMSmart = findViewById(R.id.refreshLayout);
        mRVAudioBGMSmart.setRefreshHeader(new MaterialHeader(mContext));
        mRVAudioBGMSmart.setRefreshFooter(new ClassicsFooter(mContext));
        mRVAudioBGMSmart.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                songList(true);
            }
        });
        mRVAudioBGMSmart.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                songList(false);
            }
        });
        songList(true);
    }

    /**
     * 获取音乐列表
     * @param isRefresh
     */
    public void songList(boolean isRefresh){
        GeneralUtils.songList(keywords, isRefresh, new AddOnClickListener1() {
            @Override
            public void onSkipClicked(Object mObject) {
                List<MusicList> musicListList = (List<MusicList>) mObject;
                if(isRefresh){
                    mRVAudioBGMSmart.finishRefresh();//结束刷新
                    if(null != musicListList && musicListList.size() > 0){
                        mBGMRVAdapter.setAdd(musicListList);
                    }
                }else {
                    if(null != musicListList && musicListList.size() > 0){
                        mBGMRVAdapter.add(musicListList);
                        mRVAudioBGMSmart.finishLoadMore();//结束刷新
                    }else {
                        mRVAudioBGMSmart.finishLoadMoreWithNoMoreData();//结束刷新
                    }
                }
            }
        });
    }

    /**
     * 获取音乐地址
     */
    public void playSong(int position){
        if(null == musicList){
            return;
        }
        GeneralUtils.playSong(musicList.getSid(), new AddOnClickListener1() {
            @Override
            public void onSkipClicked(Object mObject) {
                String address = (String) mObject;
                if(null != address){
                    handleBGM(position,address);
                }
            }
        });
    }

    /**
     * 播放背景
     */
    public void handleBGM(int position,String address){
        if (mAudioEffectManager == null) {
            return;
        }
        if(null == musicList){
            return;
        }
        if (mBGMId != -1) { // 已开始播放音乐，需要先停止上一次正在播放的音乐
            mAudioEffectManager.stopPlayMusic(mBGMId);
        }
        mBGMId = position;
        // 开始播放音乐时，无论是否首次均需重新设置变调和音量，因为音乐id发生了变化
        mAudioEffectManager.setMusicPitch(position, mPitch);
        mAudioEffectManager.setMusicPlayoutVolume(position, mBGMVolume);
        mAudioEffectManager.setMusicPublishVolume(position, mBGMVolume);
        //调音台
        ll_music_view.setVisibility(VISIBLE);
        //隐藏音乐列表
        ll_music_list.setVisibility(GONE);
        //选择音乐
        mBtnSelectedSong.setVisibility(GONE);
        //开始播放
        ll_music.setVisibility(VISIBLE);
        tv_bgm.setText(musicList.getTitle());
        mTvTotalTime.setText("/" + CommonUtils.formattedTime(mAudioEffectManager.getMusicDurationInMS(address)/1000) + "");
        mImgbtnBGMPlay.setImageResource(R.mipmap.icon_live_suspended);

        TXAudioEffectManager.AudioMusicParam audioMusicParam = new TXAudioEffectManager.AudioMusicParam(position, address);
        audioMusicParam.publish = true; //上行
        mAudioEffectManager.startPlayMusic(audioMusicParam);
        mBGMPlayListenr = new BGMListener();
        mAudioEffectManager.setMusicObserver(mBGMId, mBGMPlayListenr);
        mIsPlaying = true;
        mImgbtnBGMPlay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mIsPlaying){
                    mAudioEffectManager.pausePlayMusic(mBGMId);
                    mImgbtnBGMPlay.setImageResource(R.mipmap.icon_live_play);
                    mIsPlaying = false;
                }else {
                    mAudioEffectManager.resumePlayMusic(mBGMId);
                    mImgbtnBGMPlay.setImageResource(R.mipmap.icon_live_suspended);
                    mIsPlaying = true;
                }
            }
        });
    }


    private class BGMListener implements TXAudioEffectManager.TXMusicPlayObserver {

        @Override
        public void onStart(int i, int i1) {

        }

        @Override
        public void onPlayProgress(int id, final long curPtsMS, long durationMS) {
            mTvStartTime.setText(CommonUtils.formattedTime(curPtsMS /1000) + "");
        }

        @Override
        public void onComplete(int id, int i1) {
            mImgbtnBGMPlay.setImageResource(R.mipmap.icon_live_play);
            mIsPlaying = false;
        }
    }
}
